/**
 * 桩函数添加接口测试用例
 *
 * Created by snowingsea on 2020/03/07.
 */
const chai = require('chai');
const should = chai.should(); // eslint-disable-line no-unused-vars
chai.use(require('chai-http'));
const randomstring = require('randomstring');

const common = require('./../../../common');
const Administrator = require('./../../../../models/administrator');
const uri = require('./../../uri');
const benchmark = require('./../../../../benchmark/analyse-files/logic_bombs');

module.exports = describe('/POST functions/:id/stubs.json', function () {
  const administrator = new Administrator();
  const newUserIds = [];
  let projectVersion = {};
  let func = {};
  function url(functionId) {
    if (!functionId) {
      functionId = func.functionId;
    }
    return `/functions/${functionId}/stubs.json`;
  }

  before(function (done) {
    administrator.login()
      .then(() => administrator.createRandomTester())
      .then((tester) => {
        newUserIds.push(tester.userId);
        return tester.createRandomProject();
      })
      .then((project) => project.createRandomVersion())
      .then((res) => {
        projectVersion = res;
        return projectVersion.getAllFunctions(benchmark);
      })
      .then(([item]) => {
        func = item;
        done();
      })
      .catch(done);
  });
  after(function (done) {
    administrator.removeUsers(newUserIds)
      .then(() => {
        done();
      })
      .catch(done);
  });

  common.should.be.user(uri, url, 'post');
  common.should.be.tester(uri, url, 'post');

  const sampleStub1 = {
    returnType: 'int',
    paramTypeNames: ['int', 'int', 'int'],
    paramNames: ['1', '2', '3'],
    times: '7',
  };
  const sampleStub2 = JSON.parse(JSON.stringify(sampleStub1));
  delete sampleStub2.returnType;
  const sampleStub3 = JSON.parse(JSON.stringify(sampleStub1));
  delete sampleStub3.paramNames;
  const sampleStub4 = JSON.parse(JSON.stringify(sampleStub1));
  delete sampleStub4.times;
  const sampleStubs = [sampleStub1, sampleStub2, sampleStub3, sampleStub4];

  // 正常添加
  sampleStubs.forEach((sampleStub) => {
    it('it should ADD stub sccessed', function (done) {
      sampleStub.stubName = randomstring.generate({ length: 16, charset: 'alphabetic' });
      projectVersion.project.creator.login()
        .then(() => {
          chai.request(uri)
            .post(url(func.functionId))
            .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
            .query(sampleStub)
            .end((err, res) => {
              res.should.have.status(200);
              common.should.be.functionStubMessage(res.body);
              res.body.functionId.should.be.eql(func.functionId);
              res.body.stubName.should.be.eql(sampleStub.stubName);
              common.should.be.stubValidParam(res.body.params);
              done();
            });
        })
        .catch(done);
    });
  });

  // 函数不存在时，不可向其添加桩函数
  it('it should fail to add stub when the function is not exists', function (done) {
    new Promise((resovle) => {
      chai.request(uri)
        .post(url('000000000000000000000000'))
        .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
        .query(sampleStub1)
        .end((err, res) => {
          res.should.have.status(404);
          common.should.be.errorMessage(res.body);
          resovle();
        });
    })
      .then(done)
      .catch(done);
  });

  const invalidStubQuery = {
    stubName: randomstring.generate({ length: 16, charset: 'alphabetic' }),
    returnType: 'int',
    paramTypeNames: ['int', 'int', 'int'],
    paramNames: ['1', '2', '3', '4'],
    times: '7',
  };
  const invalidStubQuery2 = {
    stubName: randomstring.generate({ length: 16, charset: 'alphabetic' }),
    returnType: 'int',
    paramTypeNames: ['int', 'int', 'int'],
    paramNames: ['2', '2', '2'],
    times: '7',
  };
  const invalidQuerys = [invalidStubQuery, invalidStubQuery2];

  // paramNames非空时，如果其中存在相同的参数名，或其长度比paramTypeNames长,不可添加
  invalidQuerys.forEach((stub) => {
    it('it should not add stub for invalidStubs', function (done) {
      projectVersion.project.creator.login()
        .then(() => {
          chai.request(uri)
            .post(url(func.functionId))
            .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
            .query(stub)
            .end((err, res) => {
              res.should.have.status(400);
              common.should.be.errorMessage(res.body);
              done();
            });
        })
        .catch(done);
    });
  });

  // 不可添加他人项目的桩函数
  it('it should fail to add stub when the project is not yours', function (done) {
    let newUser;
    const stubName = randomstring.generate({ length: 16, charset: 'alphabetic' });
    administrator.createRandomTester()
      .then((tester) => {
        newUser = tester;
        newUserIds.push(tester.userId);
        return tester.getToken();
      })
      .then(() => {
        chai.request(uri)
          .post(url(func.functionId, stubName))
          .set('Authorization', `Bearer ${newUser.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(404);
            common.should.be.errorMessage(res.body);
            done();
          });
      })
      .catch(done);
  });

  // 不可添加重名的桩函数
  it('it should fail to add stub when the stubName is exists', function (done) {
    const stubName = randomstring.generate({ length: 16, charset: 'alphabetic' });
    Promise.resolve()
      .then(() => func.addStub({ stubName }))
      .then(() => {
        chai.request(uri)
          .post(url(func.functionId))
          .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
          .query({ stubName })
          .end((err, res) => {
            res.should.have.status(409);
            common.should.be.errorMessage(res.body);
            done();
          });
      })
      .catch(done);
  });
});
